package com.cd.learn.cdlearn.resttemplate;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;

/**
 * @author xuancd25
 */
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        tranceRequest(httpRequest, bytes);
        ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        traceResponse(response);
        return response;
    }

    private void tranceRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException {
        HttpHeaders headers = request.getHeaders();
        headers.add("woqu",TestContext.get());
        URI uri = request.getURI();
        System.out.println(uri.toString());
    }

    private void traceResponse(ClientHttpResponse httpResponse) throws IOException {

        HttpStatus statusCode = httpResponse.getStatusCode();
        System.out.println(statusCode);
        String statusText = httpResponse.getStatusText();
        System.out.println(statusText);

    }


}
